package com.pjb.springbootjjwt.store.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Data
@AllArgsConstructor
public class Clause {
    public static final List<String> OPS = Arrays.asList("!=", "<=", ">=", "<>", "=", ">", "<");

    private String key;     //比较键
    private String value;   //比较值
    private String op;      //操作符号

    /**
     * 操作符是否包含字符串str
     * @param str
     * 目标字符串
     * @return
     * 如果是操作符合返回是，否则非
     */
    public static boolean is(String str) {
        for (String op: OPS) {
            if (str.contains(op)) return true;
        }
        return false;
    }

    public static Clause get(String c) throws Exception {
        if (c.length() > 0)
            for (String s : OPS) {
                if (c.contains(s)) {
                    String[] pair = c.split(s);
                    String key = pair[0].trim();
                    if (key.contains("!") || key.contains("=") || key.contains(">") || key.contains("<"))
                        throw new Exception("" + Response.error.set(Error.E90005, c));
                    String value = pair[1].trim();
                    if (value.isEmpty())
                        throw new Exception("" + Response.error.set(Error.E90005, c));

                    return new Clause(key, value, s);
                }
            }
        return null;
    }

    public static List<Clause> clause(String subSql) throws Exception {
        String[] clauses = subSql.trim().split("and");
        return getClauseList(clauses);
    }

    public static List<Clause> getClauseList(String[] clauses) throws Exception {
        List<Clause> list = new ArrayList<>();
        if (clauses.length > 0) {
            for (String c : clauses) {
                c = c.replaceAll("'", "").trim();
                Clause o = Clause.get(c);
                list.add(o);
            }
        }
        System.out.println("clause:" + list);
        return list;
    }

    public static void main(String[] args) throws Exception {
        String c = " a >= b ";
        Clause clause = get(c);
        System.out.println("clause:" + clause);
        clause(" a <> 5 and c > 0 and c <> 9 and b = 2");
    }
}
